package org.fuys.coder.domain.mailbox.service.impl;

import org.fuys.coder.common.constants.RedisConstants;
import org.fuys.coder.domain.mailbox.repository.IMailBoxRepository;
import org.fuys.coder.infrastructure.util.RedisUtil;
import org.fuys.coder.domain.mailbox.model.req.MailReq;
import org.fuys.coder.domain.mailbox.model.vo.MailVO;
import org.fuys.coder.domain.mailbox.service.IMailBoxService;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @projectName: fuys-low-coder
 * @package: org.fuys.coder.domain.mailbox.service.impl
 * @className: MailBoxServiceImpl
 * @author: WangJing
 * @description: 信箱服务实现类
 * @date: 2024/7/21 15:32
 * @version: 1.0
 */

@Service
public class MailBoxServiceImpl implements IMailBoxService {

    @Resource
    private IMailBoxRepository mailBoxRepository;


    @Override
    public void publishMail(MailReq req) {
        if(ObjectUtils.isEmpty(req.getToIds())){
            return;
        }
        String redisKey= RedisConstants.REDIS_FIELD_USER+RedisConstants.REDIS_USE_INBOX
                +RedisConstants.REDIS_SPLIT+req.getToIds().get(0);
        mailBoxRepository.addMail(redisKey,req.getMailVO());
    }

    @Override
    public List<MailVO> getUserInbox(Integer userId) {
        String redisKey= RedisConstants.REDIS_FIELD_USER+RedisConstants.REDIS_USE_INBOX
                +RedisConstants.REDIS_SPLIT+userId;
        final List<Object> list = mailBoxRepository.getMailBoxInfo(redisKey);
        final List<Integer> indexes=new ArrayList<>();
        final List<MailVO> result=new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            final MailVO mailVO = (MailVO) list.get(i);
            if(mailVO.getExpire()!=null) {
                if (mailVO.getExpire() < System.currentTimeMillis()) {
                    indexes.add(i);
                } else {
                    result.add(mailVO);
                }
            }else{
                result.add(mailVO);
            }
        }
        if(!ObjectUtils.isEmpty(indexes)) {
            mailBoxRepository.clearBoxItems(redisKey,indexes);
        }
        return result;
    }

    @Override
    public void batchPublishMail(List<Integer> userIds, MailVO mail) {
        if(ObjectUtils.isEmpty(userIds)||ObjectUtils.isEmpty(mail.getData())){
            return;
        }
        List<String> redisKeys=new ArrayList<>();
        userIds.forEach(item->{
            String redisKey=RedisConstants.REDIS_FIELD_USER+RedisConstants.REDIS_USE_INBOX
                    +RedisConstants.REDIS_SPLIT;
            redisKeys.add(redisKey+item);
        });
        mailBoxRepository.addMailToUsers(redisKeys,mail);
    }
}
